package com.sqx.modules.timedtask;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.common.utils.DateUtils;
import com.sqx.modules.app.dao.SysEvaluateDao;
import com.sqx.modules.app.entity.SysEvaluate;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.goods.dao.GoodsDao;
import com.sqx.modules.goods.entity.Goods;
import com.sqx.modules.message.dao.MessageInfoDao;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.tbCoupon.entity.TbCouponUser;
import com.sqx.modules.tbCoupon.service.TbCouponUserService;
import com.sqx.modules.tbOrders.dao.TbOrdersDao;
import com.sqx.modules.tbOrders.entity.TbOrders;
import com.sqx.modules.tbOrders.service.TbOrdersService;
import com.sqx.modules.utils.SenInfoCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.Temporal;
import java.util.Date;
import java.util.List;


@Component
@Slf4j
public class TimedTask {
    @Autowired
    private UserService userService;
    @Autowired
    private TbOrdersService ordersService;
    @Autowired
    private TbOrdersDao ordersDao;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private MessageInfoDao messageInfoDao;
    @Autowired
    private TbCouponUserService couponUserService;
    @Autowired
    private SysEvaluateDao sysEvaluateDao;
    @Autowired
    private GoodsDao baseMapper;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;

    /**
     * 待支付取消订单
     */
    @Scheduled(cron = "0/2 * * * * ?", zone = "Asia/Shanghai")
    public void waitPayCancelOrder() {
        List<TbOrders> tbOrdersList = ordersService.list(new QueryWrapper<TbOrders>()
                .eq("status", 0)
                .eq("retrieve_type", 1));
        int minute = Integer.parseInt(commonInfoService.findOne(417).getValue());
        for (TbOrders order : tbOrdersList) {
            ZonedDateTime now = LocalDateTime.now().atZone(ZoneId.systemDefault());
            Duration duration = Duration.between(order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()), now);
            if (duration.toMinutes() > minute) {
                //将优惠券修改为未使用状态
                if (order.getCouponId() != null) {
                    TbCouponUser couponUser = couponUserService.getById(order.getCouponId());
                    if (couponUser != null) {
                        couponUser.setStatus(0);
                        couponUserService.updateById(couponUser);
                    }
                }
                Goods goods = baseMapper.selectById(order.getGoodId());
                if (goods != null && goods.getStockId() != null) {
                    goods.setStock(goods.getStock() + order.getBuyNum());
                    baseMapper.updateById(goods);
                }else if (goods != null && goods.getIsStock() != null && goods.getIsStock() == 2) {
                    goods.setStock(goods.getStock() + order.getBuyNum());
                    baseMapper.updateById(goods);
                }
                order.setStatus(5);
                order.setCancelTime(new Date());
                ordersService.updateById(order);
            }
        }
    }

    /**
     * 自动检测评价，超过7天未评价则自动5星好评
     */
    @Scheduled(cron = "0/2 * * * * ?", zone = "Asia/Shanghai")
    public void checkOrderEvaluation() {
        List<TbOrders> tbOrdersList = ordersService.list(new QueryWrapper<TbOrders>()
                .in("status", 3, 7)
                .eq("is_evaluate", 0));
        int days = Integer.parseInt(commonInfoService.findOne(514).getValue());
        for (TbOrders order : tbOrdersList) {
            ZonedDateTime now = LocalDateTime.now().atZone(ZoneId.systemDefault());
            if (order.getDealTime() != null) {
                Duration duration = Duration.between(order.getDealTime().toInstant().atZone(ZoneId.systemDefault()), now);
                if (duration.toDays() + 1 > days) {
                    //7天未评价，自动好评
                    SysEvaluate evaluate = new SysEvaluate();
                    if (order.getRetrieveType() == 0) {
                        evaluate.setUserId(order.getSellerId());
                        evaluate.setRecycleStatus(1);
                        order.setIsEvaluate(1);
                        ordersService.updateById(order);
                    } else {
                        evaluate.setUserId(order.getBuyerId());
                        evaluate.setRecycleStatus(0);
                        order.setStatus(4);
                        order.setIsEvaluate(1);
                        ordersService.updateById(order);
                    }
                    evaluate.setIsDelete(0);
                    evaluate.setFeedbackStatus(1);
                    evaluate.setSatisfactionFlag(5);
                    evaluate.setIndentNumber(order.getOrderNumber());
                    evaluate.setEvaluateMessage("系统自动好评");
                    evaluate.setCreateTime(new Date());
                    sysEvaluateDao.insert(evaluate);

                }
            }
        }
    }

    /**
     * 自动检测确认收货，超过7天未收货则自动收货
     */
    @Scheduled(cron = "0/2 * * * * ?", zone = "Asia/Shanghai")
    public void checkOrderReceivingOrder() {
        List<TbOrders> tbOrdersList = ordersService.list(new QueryWrapper<TbOrders>()
                .eq("status", 2)
                .in("delivery_status", 0, 1)
                .last("FOR UPDATE"));
        int days = Integer.parseInt(commonInfoService.findOne(522).getValue());
        for (TbOrders order : tbOrdersList) {
            ZonedDateTime now = LocalDateTime.now().atZone(ZoneId.systemDefault());
            if (order.getSendTime() != null) {
                Duration duration = Duration.between(order.getSendTime().toInstant().atZone(ZoneId.systemDefault()), now);
                if (duration.toDays() + 1 > days) {
                    //7天未收货，自动确认收货
                    order.setStatus(3);
                    order.setDealTime(new Date());
                    int result = ordersDao.updateById(order);
                    if (result > 0) {
                        UserEntity user = userService.selectUserById(order.getSellerId());
                        if (user != null) {
                            user.setBalance(user.getBalance().add(order.getSellerIncome()));
                            userService.updateByUserId(user.getUserId(), order.getSellerIncome().doubleValue());
                            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                            userMoneyDetails.setUserId(order.getSellerId());
                            userMoneyDetails.setMoney(order.getSellerIncome());
                            userMoneyDetails.setClassify(1);
//                userMoneyDetails.setUserLevel(2);
                            userMoneyDetails.setRelationId(order.getOrderId());
                            userMoneyDetails.setType(1);
                            userMoneyDetails.setTitle("收入订单:" + order.getOrderNumber());
                            userMoneyDetails.setContent("订单号:" + order.getOrderNumber() + ",订单总价:" + order.getTotalPrice() + ",本单收入:" + order.getSellerIncome());
                            userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
                            userMoneyDetailsService.save(userMoneyDetails);
                            if (user.getCreditScore() < 100) {
                                user.setCreditScore(user.getCreditScore() + 1);
                                UserMoneyDetails userMoneyDetails1 = new UserMoneyDetails();
                                userMoneyDetails1.setUserId(order.getSellerId());
                                userMoneyDetails1.setRelationId(order.getOrderId());
                                userMoneyDetails1.setType(1);
                                userMoneyDetails1.setClassify(5);
                                userMoneyDetails1.setTitle("订单：" + order.getOrderNumber());
                                userMoneyDetails1.setContent("用户购买订单，增加信用分：" + 1);
                                userMoneyDetails1.setCreateTime(DateUtils.format(new Date()));
                                userMoneyDetailsService.save(userMoneyDetails1);
                                userService.updateById(user);
                            }
                            ordersService.setCommission(order.getOrderId(), 1);
                        }
                        UserEntity userEntity = userService.selectUserById(order.getBuyerId());
                        if (userEntity != null) {
                            MessageInfo messageInfo = new MessageInfo();
                            messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                            messageInfo.setTitle("您超过收货时间，系统已自动确认收货，订单：" + order.getOrderNumber());
                            messageInfo.setContent("您的订单已确认收货");
                            messageInfo.setUserName(userEntity.getUserName());
                            messageInfo.setCreateAt(DateUtils.format(new Date()));
                            messageInfo.setIsSee("0");
                            messageInfo.setStatus(0);
                            messageInfo.setState(String.valueOf(6));
                            messageInfoDao.insert(messageInfo);
                        }
                        Goods goods = baseMapper.selectById(order.getGoodId());
                        if (goods != null) {
                            goods.setOutStock(goods.getOutStock() + order.getBuyNum());
                            baseMapper.updateById(goods);
                        }
                    }
                }
            }
        }
    }

    /**
     * 查询置顶商品是否到期
     */
    @Scheduled(cron = "0/5 * * * * ?", zone = "Asia/Shanghai")
    public void checkGoodsTop() {
        List<Goods> goodList = baseMapper.selectList(new QueryWrapper<Goods>()
                .eq("is_top", 1)
                .eq("status", 1)
                .eq("is_enable", 1)
                .eq("good_status", 0));
        String minute = commonInfoService.findOne(518).getValue();
        String[] minuteValues = minute.split(",");
        int minuteCount = 0;
        if (minuteValues.length > 1) {
            minute = minuteValues[0];
            minuteCount = Integer.parseInt(minute);
        }
        for (Goods good : goodList) {
            ZonedDateTime now = LocalDateTime.now().atZone(ZoneId.systemDefault());
            Duration duration = Duration.between(good.getTopStartTime().toInstant().atZone(ZoneId.systemDefault()), now);
            if (duration.toMinutes() >= minuteCount) {
                // 如果置顶时间超过设定值，则置顶状态改为已取消
                good.setIsTop(0);
                good.setTopEndTime(new Date());
                baseMapper.updateById(good);
            }
        }
    }


}
